package com.angel.bo.auth.client.jwt;


import com.angel.bo.auth.client.exception.AuthException;
import com.angel.bo.auth.client.properties.AuthProperties;
import com.angel.bo.beans.jwt.JwtInfo;
import com.angel.bo.common.constant.ReturnCode;
import com.angel.bo.common.context.CommonContextHandler;
import com.angel.bo.common.util.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.SignatureException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.angel.bo.common.constant.CommonConstants.CONTEXT_KEY_USER_TOKEN;

/**
 * @Author: Haibo.Mei [Haibo.Mei@ge.com]
 * @Description: 客户端token工具类
 * @Date: 11:18 2018/1/30
 */
@Component
public class AuthUtil {


    @Autowired
    private AuthProperties authProperties;

    public JwtInfo getJwtFromToken(String token) throws Exception {
        try {
            return JwtUtil.getInfoFromToken(token, authProperties.getPubKey().getPath());
        } catch (ExpiredJwtException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_EXPIRED);
        } catch (SignatureException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_ERROR);
        } catch (IllegalArgumentException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_NULL);
        } catch (Exception e) {
            throw new AuthException(ReturnCode.USER_TOKEN_ERROR);
        }
    }

    /**
     * @Author: Haibo.Mei [Haibo.Mei@ge.com]
     * @Description: 生成token
     * @Date: 11:26 2018/1/31
     */
    public String generateToken(JwtInfo jwtInfo) {
        try {
            String token = JwtUtil.generateToken(jwtInfo, authProperties.getPriKey().getPath(), authProperties.getExpire());
            return token;
        } catch (Exception e) {
            throw new AuthException(ReturnCode.GENERATE_TOKEN_ERROR);
        }
    }

    /**
     * 根据token获取当前用户ID
     * @return
     * @throws Exception
     */
    public Integer getUserIdFromToken(){
        String token = (String) CommonContextHandler.get(CONTEXT_KEY_USER_TOKEN);
        JwtInfo jwtInfo = null;
        try {
            jwtInfo = JwtUtil.getInfoFromToken(token, authProperties.getPubKey().getPath());
        }  catch (ExpiredJwtException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_EXPIRED);
        } catch (SignatureException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_ERROR);
        } catch (IllegalArgumentException ex) {
            throw new AuthException(ReturnCode.USER_TOKEN_NULL);
        } catch (Exception e) {
            throw new AuthException(ReturnCode.USER_TOKEN_ERROR);
        }
        return Integer.parseInt(jwtInfo.getUserId());
    }
}
